package com.huitong.common.core.factory;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;

/**
 * 配置资源文件源工厂
 *
 * @author fromdrowning
 * @date 2024/3/16 16:19
 */
public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {

    /**
     * 配置处理资源文件的对象
     *
     * @param name     资源文件名
     * @param resource 资源文件路径
     * @return 处理资源文件的对象
     * @throws IOException 处理资源文件失败抛出此异常
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = resource.getResource().getFilename();
        if (StrUtil.isNotBlank(sourceName) && StrUtil.endWithAny(sourceName, ".yml", ".yaml")) {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return new PropertiesPropertySource(sourceName, factory.getObject());
        }
        return super.createPropertySource(name, resource);
    }
}
